//
//  MHPickerSheetView.swift
//  Kool Car
//
//  Created by huangweiqiang on 2022/2/12.
//

import UIKit
///Any: 选中的字符
///NSInteger： 选中的下标
/// Bool：false 取消 / true:确定
typealias MHPickerSheetViewBlock = (Any, NSInteger, Bool) -> ()

class MHPickerSheetView: UIViewController {
    var callBack: MHPickerSheetViewBlock!
    var closeDurationFlag: Bool = true
    var showHeaderFlag: Bool = true
    var headerView: UIView!
    var footerView: UIView!
    var selectIndex = 99999 //记录选中的
    var bkgBtn: UIButton!
    var contentView: UIView! //装载tableView背景圆角时用
    var titleStr: String = ""
    var pickerView: UIPickerView!
    var dataArray: [Any] = []
    var selectItem: Any!
    override func viewDidLoad() {
        super.viewDidLoad()
        if ((self.selectItem as? BrandSeriesListModel) != nil) {
            for (tagIndex, kItem) in self.dataArray.enumerated() {
                if (kItem as! BrandSeriesListModel).id == (self.selectItem as! BrandSeriesListModel).id {
                    self.selectIndex = tagIndex
                    break
                }
            }
        }else if (self.selectItem as? SeriesListModel) != nil {
            for (tagIndex, kItem) in self.dataArray.enumerated() {
                if (kItem as! SeriesListModel).id == (self.selectItem as! SeriesListModel).id {
                    self.selectIndex = tagIndex
                    break
                }
            }
        } else if ((self.selectItem as? String) != nil) {
            for (tagIndex, kItem) in self.dataArray.enumerated() {
                if (kItem as! String) == (self.selectItem as! String) {
                    self.selectIndex = tagIndex
                    break
                }
            }
        }
        
        //背景蒙层
        self.view.backgroundColor = UIColor.clear
        bkgBtn = UIButton.init(type: UIButtonType.custom)
        bkgBtn.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
        bkgBtn.backgroundColor =  UIColor.init(R: 0, G: 0, B: 0, alpha: 0)
        bkgBtn.addTarget(self, action: #selector(hiddenActionView), for: .touchUpInside)
        self.view.addSubview(bkgBtn)
        
        ///
        self.contentView = UIView.init(frame: CGRect.init(x: 0, y: kScreenHeight, width: kScreenWidth, height: kScreenHeight))
        self.contentView.backgroundColor = UIColor.white
        self.bkgBtn.addSubview(self.contentView)
        
        self.headerView = self.setUpHeaderView()
        self.footerView = self.setUpFooterView()
        self.contentView.addSubview(self.headerView)
        self.contentView.addSubview(self.footerView)

        pickerView = UIPickerView.init(frame: CGRect.init(x: 0, y: self.headerView.frame.maxY, width: kScreenWidth, height: 0))
        pickerView.delegate = self
        pickerView.dataSource = self
        self.contentView.addSubview(pickerView)
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.startAnimationAction()

    }
    ///顶部 TitleLabel有半圆
    func setUpHeaderView() -> UIView {
        let tempH: CGFloat = self.showHeaderFlag ? 0 : 56
        let tempHeaderView = UIView.init(frame: CGRect.init(x: 0, y: kScreenHeight, width: kScreenWidth, height: tempH))
        if self.showHeaderFlag {
            //做圆角背景
            tempHeaderView.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 56)
            tempHeaderView.backgroundColor = UIColor.white
            tempHeaderView.round(byRoundingCorners: UIRectCorner.init(arrayLiteral: .topLeft, .topRight), cornerRadi: 10)
            
            let tempTitleLab = UILabel.init(frame: CGRect.init(x: kScreenWidth/2 - 160, y: 0, width: 320, height: 56))
            tempTitleLab.backgroundColor = UIColor.clear
            tempTitleLab.textAlignment = .center
            tempTitleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
            tempTitleLab.textColor = Theme.titleLabColor
            tempTitleLab.numberOfLines = 0
            tempTitleLab.text = self.titleStr
            tempHeaderView.addSubview(tempTitleLab)
            
            let lineView = UIView.init(frame: CGRect.init(x: 0, y: tempHeaderView.frame.size.height - 0.5, width: kScreenWidth, height: 0.5))
            lineView.backgroundColor = UIColor.init(hex: 0xF2F7FA)
            tempHeaderView.addSubview(lineView)
            
            //取消按钮和确认按钮在顶部
            let cancelBtn = UIButton.init(frame: CGRect.init(x: 14, y: 8, width: 100, height: 40))
            cancelBtn.setTitle(MMLocalizedString("cancel", comment: "取消"), for: .normal)
            cancelBtn.setTitle(MMLocalizedString("cancel", comment: "取消"), for: .selected)
            cancelBtn.setTitleColor(Theme.mainColor, for: .normal)
            cancelBtn.setTitleColor(Theme.mainColor, for: .normal)
            cancelBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 16)
            cancelBtn.addTarget(self, action: #selector(hiddenActionView), for: .touchUpInside)
            cancelBtn.contentHorizontalAlignment = .left
            cancelBtn.backgroundColor = .clear
            tempHeaderView.addSubview(cancelBtn)
            
            let okBtn = UIButton.init(frame: CGRect.init(x: tempHeaderView.frame.size.width - 114, y: 8, width: 100, height: 40))
            okBtn.setTitle(MMLocalizedString("finish", comment: "完成"), for: .normal)
            okBtn.setTitle(MMLocalizedString("finish", comment: "完成"), for: .selected)
            okBtn.setTitleColor(Theme.mainColor, for: .normal)
            okBtn.setTitleColor(Theme.mainColor, for: .normal)
            okBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 16)
            okBtn.addTarget(self, action: #selector(okBtnAction), for: .touchUpInside)
            okBtn.contentHorizontalAlignment = .right
            okBtn.backgroundColor = .clear
            tempHeaderView.addSubview(okBtn)
        }
        return tempHeaderView
    }
    
    ///确定
    @objc func okBtnAction(){
        let curIndex = self.pickerView.selectedRow(inComponent: 0)
        if self.dataArray.count > curIndex {
            let tempData = self.dataArray[curIndex]
            UIView.animate(withDuration:  0.2, delay: 0, options: .curveLinear, animations: {
                self.bkgBtn.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0)
                self.contentView.frame.origin.y = kScreenHeight
            }, completion: { _ in
                self.dismiss(animated: false) {
                    self.callBack?(tempData, curIndex, true)
                }
            })
        }
    }
    
    ///底部取消按钮
    func setUpFooterView() -> UIView {
        let aView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: IphoneXMarginBottom))
        aView.backgroundColor = .white
        return aView
    }
    
    ///页面展示动画
    @objc func startAnimationAction(){
        let tempHH: CGFloat = 210
        self.pickerView.frame.size.height = tempHH
        let headerFooter = self.headerView.frame.size.height + self.footerView.frame.size.height
        self.contentView.frame.size.height = tempHH + headerFooter
        self.contentView.round(byRoundingCorners: UIRectCorner.init(arrayLiteral: .topLeft, .topRight), cornerRadi: 6)

        self.headerView.frame.origin = CGPoint.init(x: 0, y: 0)
        self.pickerView.frame.origin = CGPoint.init(x: 0, y: self.headerView.frame.maxY)
        self.footerView.frame.origin = CGPoint.init(x: 0, y: self.pickerView.frame.maxY)
        
        let opts = UIViewAnimationOptions.curveEaseInOut
        UIView.animate(withDuration: 0.3, delay: 0, options: opts, animations: {
            self.bkgBtn.backgroundColor =  UIColor.init(R: 0, G: 0, B: 0, alpha: 0.4)
            self.contentView.frame.origin.y = kScreenHeight - tempHH - headerFooter
        }, completion: { _ in
            if self.titleStr == "" {
                //第一行做圆角处理
            }
            //移动到当前cell
            if self.selectIndex != -1 && self.dataArray.count > self.selectIndex {
                self.pickerView.reloadAllComponents()
                self.pickerView.selectRow(self.selectIndex, inComponent: 0, animated: false)
            }
        })
    }
    
    /// 隐藏,没有点添加到购物车按钮
    @objc func hiddenActionView(){
        let opts = UIViewAnimationOptions.curveEaseInOut
        UIView.animate(withDuration: 0.24, delay: 0, options: opts, animations: {
            self.bkgBtn.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0)
            self.contentView.frame.origin.y = kScreenHeight
        }, completion: { _ in
            self.dismiss(animated: false) {
                if self.selectItem != nil {
                    self.callBack(self.selectItem, self.selectIndex, false)
                }
            }
        })
    }
    
    @objc func cancelBtnAction(){
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            self.hiddenActionView()
        }
    }

}


extension MHPickerSheetView: UIPickerViewDelegate, UIPickerViewDataSource {
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.dataArray.count
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return "\(row)"
    }
    
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 58
    }
  
    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return kScreenWidth
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let centerView = pickerView.subviews.last
        if centerView != nil {
            centerView?.frame = CGRect.init(x: -1, y: centerView?.frame.origin.y ?? 76, width: kScreenWidth+1, height: centerView?.frame.size.height ?? 58)
            centerView?.backgroundColor = UIColor.clear
            centerView?.layer.borderColor = UIColor.init(hex: 0xE1E3E6, alpha: 1).cgColor
            centerView?.layer.borderWidth = 0.5
            centerView?.layer.cornerRadius = 0
        }
        let titleLab = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 58))
        titleLab.backgroundColor = UIColor.white
        titleLab.textAlignment = .center
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 18)
        if self.dataArray.count > row {
            let item = self.dataArray[row]
             if ((item as? String) != nil) {
                titleLab.text = item as? String
            }
        }
        titleLab.textColor = Theme.titleLabColor
        return titleLab
    }
}
